﻿using Ldt.InformationUnit.Common;
using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.DataSave;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.OptimizationModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.CommModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace LdtDataEngin.ModuleDetail.CaseElmentOpt
{
    public class CaseOptimization : OptimizationBase
    {
        /// <summary>
        /// 阶段信息
        /// </summary>
        private StageConfig stageModelConfig = new StageConfig();

        public List<DataModel> dataModelsOPList = new List<DataModel>();

        /// <summary>
        /// 文书定位信息
        /// </summary>
        private List<DOCLocationModel> locationModelList;


        public CaseOptimization(DataContext context, string moudleName)
        {
            dataContext = context;
            this.ModuleName = moudleName;
            var configModel = dataContext.DataLayerSys.GetConfigModel(moudleName);
            var caseXmlContst = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "caseoptimize").ConfigContent.ToString();
            var stageConfig = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "stagelocate");
            if (stageConfig != null && !string.IsNullOrEmpty(stageConfig.ConfigContent))
            {
                stageModelConfig = XmlUtility.DeserializeToObject<StageConfig>(stageConfig.ConfigContent);
            }
            if (!string.IsNullOrWhiteSpace(caseXmlContst))
            {
                OptimizConfig = XmlUtility.DeserializeToObject<OptimizeConfig>(caseXmlContst);
            }
            var docmergeoptconfig = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "docmergeopt");
            if (docmergeoptconfig != null && !string.IsNullOrWhiteSpace(docmergeoptconfig.FilePath))
            {
                if (!string.IsNullOrWhiteSpace(docmergeoptconfig.FilePath))
                {
                    string url = docmergeoptconfig.FilePath.Replace("{sourcecode}", dataContext.DataLayerAns.SourceCode.ToLower()).Replace(" ", ""); ;//dataContext.DataLayerAns.CaseCausesList[0].CC_ID

                    Dictionary<string, string> dicElement = new Dictionary<string, string>();
                    dicElement.Add("fileFullName", url);
                    string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");//ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi")
                    dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                    if (elementcofig.result.code.ToString() == "1")
                    {
                        docmergeopt = elementcofig.body;

                    }
                }
            }
            var multipledocjudgeconfig = configModel.ConfigDetail.FirstOrDefault(a => a.Code.ToLower() == "multipledocjudge");
            if (multipledocjudgeconfig != null && !string.IsNullOrWhiteSpace(multipledocjudgeconfig.ConfigContent))
            {
                multipledocjudge = multipledocjudgeconfig.ConfigContent;
            }
            string causeLocalContent = "";
            string causeStageContent = "";
            var causeLocalConfig = configModel.ConfigDetail.FirstOrDefault(x => x.ExecuteCode == "elementpath.xml");
            if (causeLocalConfig != null)
                causeLocalContent = causeLocalConfig.ConfigContent;
            var causeStageConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "causestagelocation");
            if (causeStageConfig != null)
                causeStageContent = causeStageConfig.ConfigContent;
            locationModelList = GetLocationModels(causeLocalContent, causeStageContent);

            try
            {
                DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
                var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
                if (anjiancunchuList.Count > 0)
                {//anjiancunchuList[0].Wenjianid
                    string b = "781f18610b23430b83e952feaa67cc02";
                    string c = "3de7c9d6d646475ab448158e256e938b";
                    DataSoursModel dataSoursModel = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                    dataModelsOPList = dataSoursModel.dataModelList;
                   XmlDocument doc = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
                    foreach (DataModel mode in dataModelsOPList)
                    {
                        foreach (Source item in mode.sourceData.sourceList)
                        {
                            item.AnalysisStatus = "1";
                        }
                    }
                }
                if (stageModelConfig != null && stageModelConfig.evidenceModelList != null && stageModelConfig.evidenceModelList.Count > 0)
                {
                    DelectEvidenData(stageModelConfig.evidenceModelList[0].path, dataModelsOPList);
                    
                }

            }
            catch (Exception)
            {

                dataContext.InteractiveShow.LogShow("案件要素优选数据库优选，数据初始化失败，直接转换为优选结果");
            }


        }

        /// <summary>
        /// 删除证据与事实对应关系，并存储于对应节点
        /// </summary>
        public void DelectEvidenData(string path, List<DataModel> modelList)
        {

            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            dataContext.InteractiveShow.LogShow("开始转移证据与事实要素关系节点");
            if (modelList.Count > 0)
            {
                List<DataModel> evidList = XmlUtility.ConditionDataModelList(modelList, "", path);
                foreach (DataModel model in evidList)
                {
                    List<DataModel> evidenModelList = xmlUtilCommon.SubordinateDataModelList(modelList, model);
                    for (int i = 0; i < evidenModelList.Count; i++)
                    {
                        modelList.Remove(evidenModelList[i]);
                    }
                    dataContext.DataLayerSys.dicEviden.Add(model.ParentId, evidenModelList);
                }

            }

        }

        /// <summary>
        /// 跨阶段信息加载
        /// </summary>
        public void SateLoadeOptimization(List<DataModel> dataModelsOPList, List<DataModel> dataModelAsisList)
        {
            List<StageProcessModel> stageProcessModelList = new List<StageProcessModel>();
            if (dataModelsOPList != null && dataModelsOPList.Count > 0)
            {
                #region 优选结果阶段数据
                if (stageModelConfig != null && stageModelConfig.stageModelList != null && stageModelConfig.stageModelList.Count > 0)
                {
                    stageProcessModelList = LoadeStageData(stageModelConfig, dataModelsOPList);
                    if (stageProcessModelList.Count > 0)
                    {
                        dataContext.DataLayerOpt.StageProcessResultModel = stageProcessModelList.OrderByDescending(a => a.id).ToList()[0];
                    }
                }
                else
                {
                    dataContext.InteractiveShow.LogShow("优选结果：阶段数据并无跨阶段优选配置。");
                }
                #endregion
            }

            #region 分析结果数据阶段数据

            if (dataModelAsisList != null && dataModelAsisList.Count > 0)
            {
                if (dataContext.DataLayerAns.StageProcessAnalysisDataModel == null)
                {
                    if (stageModelConfig != null && stageModelConfig.stageModelList != null && stageModelConfig.stageModelList.Count > 0)
                    {
                        stageProcessModelList = LoadeStageData(stageModelConfig, dataModelAsisList);
                        if (stageProcessModelList.Count > 0)
                        {
                            dataContext.DataLayerAns.StageProcessAnalysisDataModel = stageProcessModelList.OrderByDescending(a => a.id).ToList()[0];
                            if (dataContext.DataLayerOpt.StageProcessResultModel != null && dataContext.DataLayerAns.StageProcessAnalysisDataModel.id == 0)
                            {
                                //当分析结果为255时处理
                                DataModel dataAmodel = dataModelAsisList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == "阶段") != null);
                                if (dataAmodel != null && dataContext.DataLayerOpt.StageProcessResultModel != null)
                                {
                                    dataAmodel.AttributesList.FirstOrDefault(a => a.Name == "阶段").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = dataContext.DataLayerOpt.StageProcessResultModel.stageName;
                                }
                                stageProcessModelList = LoadeStageData(stageModelConfig, dataModelAsisList);
                                if (stageProcessModelList.Count > 0)
                                {
                                    dataContext.DataLayerAns.StageProcessAnalysisDataModel = stageProcessModelList.OrderByDescending(a => a.id).ToList()[0];
                                }

                            }
                        }
                    }
                    else
                    {
                        dataContext.InteractiveShow.LogShow("提取结果：阶段数据并无跨阶段优选配置。");
                    }
                }
            }
            #endregion

            #region 传入阶段数据实体
            if (!string.IsNullOrEmpty(dataContext.DataLayerAns.SatgeAnalysis))
            {
                if (stageModelConfig != null && stageModelConfig.stageModelList != null && stageModelConfig.stageModelList.Any())
                {
                    var model = stageModelConfig.stageModelList.FirstOrDefault(a => a.value == dataContext.DataLayerAns.SatgeAnalysis);
                    if (model != null)
                    {
                        StageProcessModel stageProcessModel = new StageProcessModel();
                        stageProcessModel.id = Convert.ToInt32(model.id);
                        stageProcessModel.Analysisresults = true;
                        stageProcessModel.path = model.path;
                        stageProcessModel.dataModel = new DataModel();
                        dataContext.DataLayerAns.StageProcessAnalysisModel = stageProcessModel;
                        if (dataContext.DataLayerOpt.StageProcessResultModel != null && model.id == "0")
                        {

                            //传入 A255时更新阶段为最新阶段
                            dataContext.DataLayerAns.StageProcessAnalysisModel = new StageProcessModel();
                            stageProcessModel.id = dataContext.DataLayerOpt.StageProcessResultModel.id;
                            stageProcessModel.Analysisresults = true;
                            stageProcessModel.path = dataContext.DataLayerOpt.StageProcessResultModel.path;
                            stageProcessModel.dataModel = new DataModel();
                            dataContext.DataLayerAns.StageProcessAnalysisModel = dataContext.DataLayerOpt.StageProcessResultModel;
                            if (dataContext.DataLayerAns.StageProcessAnalysisDataModel != null)
                            {
                                if (dataContext.DataLayerAns.StageProcessAnalysisDataModel.id > dataContext.DataLayerOpt.StageProcessResultModel.id)
                                {
                                    dataContext.DataLayerAns.StageProcessAnalysisModel = dataContext.DataLayerAns.StageProcessAnalysisDataModel;
                                }
                            }
                        }
                    }
                    else
                    {
                        dataContext.InteractiveShow.LogShow("推送结果：推送结果并无阶段数据！！！");
                    }
                }
                else
                {
                    dataContext.InteractiveShow.LogShow("推送结果：推送结果并无阶段数据！！！");
                }
            }
            else
            {
                dataContext.InteractiveShow.LogShow("传入案件阶段为空！！！！！");
                if (dataContext.DataLayerAns.StageProcessAnalysisDataModel != null)
                {
                    dataContext.InteractiveShow.LogShow("传入案件阶段为空！！！！！将传入空案件阶段赋值" + dataContext.DataLayerAns.StageProcessAnalysisDataModel.id);
                    //传入阶段数据为空
                    StageProcessModel stageProcessModel = new StageProcessModel();
                    stageProcessModel.id = Convert.ToInt32(dataContext.DataLayerAns.StageProcessAnalysisDataModel.id);
                    stageProcessModel.Analysisresults = true;
                    stageProcessModel.path = dataContext.DataLayerAns.StageProcessAnalysisDataModel.path;
                    stageProcessModel.dataModel = new DataModel();
                    dataContext.DataLayerAns.StageProcessAnalysisModel = stageProcessModel;
                }

            }
            #endregion

        }
       
        /// <summary>
        /// 优选操作
        /// </summary>
        public void Optimization()
        {
            Stopwatch stopwatch = new Stopwatch();
            SetModuleProcess(ModuleName, 0, dataContext.InteractiveShow.inputParameterModel);
            stopwatch.Start();
           
            DOCLocationModel dOCLocationModel = new DOCLocationModel();
            if (locationModelList!=null && locationModelList.Count>0)
            {
                dOCLocationModel = locationModelList.FirstOrDefault(a => a.DocType == dataContext.DataLayerAns.SourceCode);
            }
            //分析数据结果
            List<DataModel> dataModelAsisList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList));
            FilterCaseElment(dataModelAsisList);
            try
            {
                MergConfig(dataModelAsisList, dataModelsOPList, "1");
            }
            catch (Exception ex)
            {

                dataContext.InteractiveShow.LogShow("删除错误");
            }
            //上次优选结果数据

            if (dataContext.DataLayerOpt.AnalysisResultsDataModel != null && dataContext.DataLayerOpt.AnalysisResultsDataModel.Count > 0)
            {
                dataModelsOPList = dataContext.DataLayerOpt.AnalysisResultsDataModel;
            }
            else if (!string.IsNullOrWhiteSpace(dataContext.DataLayerOpt.CaseId))
            {
                //try
                //{
                //    DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
                //    var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
                //    if (anjiancunchuList.Count > 0)
                //    {
                //        DataSoursModel dataSoursModel = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                //        dataModelsOPList = dataSoursModel.dataModelList;
                //    }
                //}
                //catch (Exception)
                //{
                //    dataContext.InteractiveShow.LogShow("案件要素优选数据库优选，数据初始化失败，直接转换为优选结果");
                //}
            }
            SateLoadeOptimization(dataModelsOPList, dataModelAsisList);
            #region TODO:ZSW 版本合并旧逻辑
            ////跨阶段优选值都不为空，并且优选结果阶段大于传入阶段时，不进行案件要素优选。直接进入跨阶段优选
            //if (dataContext.DataLayerAns.StageProcessAnalysisModel != null && dataContext.DataLayerAns.StageProcessAnalysisDataModel != null
            //    && dataContext.DataLayerAns.StageProcessAnalysisModel.id > dataContext.DataLayerAns.StageProcessAnalysisDataModel.id)
            //{
            //    dataContext.InteractiveShow.LogShow("新数据阶段小于传入阶段数据阶段，不进行案件数据优选");

            //    dataContext.InteractiveShow.LogShow("开始计算通用信息");
            //    List<DataModel> dataRomveList = XmlUtility.ConditionDataModelList(dataModelAsisList, "", dOCLocationModel.DocPath);
            //    if (dataRomveList != null && dataRomveList.Count > 0)
            //    {
            //        foreach (var datamodel in dataRomveList)
            //        {
            //            dataModelAsisList.Remove(datamodel);
            //        }
            //    }
            //}
            //if (dataContext.DataLayerAns.StageProcessAnalysisDataModel != null && dataContext.DataLayerOpt.StageProcessResultModel != null && dataContext.DataLayerAns.StageProcessAnalysisDataModel.id == 0 && dataContext.DataLayerAns.StageProcessAnalysisDataModel.id < dataContext.DataLayerOpt.StageProcessResultModel.id)
            //{
            //    dataContext.InteractiveShow.LogShow("新数据阶段小于传入阶段数据阶段，不进行案件数据优选");
            //    List<DataModel> dataRomveList = XmlUtility.ConditionDataModelList(dataModelAsisList, "", dOCLocationModel.DocPath);
            //    if (dataRomveList != null && dataRomveList.Count > 0)
            //    {
            //        foreach (var datamodel in dataRomveList)
            //        {

            //            dataModelAsisList.Remove(datamodel);
            //        }
            //    }
            //}
            #endregion
            //跨阶段优选值都不为空，并且优选结果阶段大于传入阶段时，不进行案件要素优选。直接进入跨阶段优选
            if (dataContext.DataLayerAns.StageProcessAnalysisModel != null && dataContext.DataLayerAns.StageProcessAnalysisDataModel != null
                && dataContext.DataLayerAns.StageProcessAnalysisModel.id > dataContext.DataLayerAns.StageProcessAnalysisDataModel.id)
            {
                dataContext.InteractiveShow.LogShow("新数据阶段小于传入阶段数据阶段，不进行案件数据优选");
                dataContext.DataLayerOpt.SourdatModleList = new List<DataModel>();
                dataContext.DataLayerOpt.SourdatModleList.AddRange(dataModelsOPList);
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList);
                stopwatch.Stop();
                SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
                return;
            }
            if (dataContext.DataLayerAns.StageProcessAnalysisDataModel != null && dataContext.DataLayerOpt.StageProcessResultModel != null && dataContext.DataLayerAns.StageProcessAnalysisDataModel.id == 0 && dataContext.DataLayerAns.StageProcessAnalysisDataModel.id < dataContext.DataLayerOpt.StageProcessResultModel.id)
            {
                dataContext.InteractiveShow.LogShow("新数据阶段小于传入阶段数据阶段，不进行案件数据优选");
                dataContext.DataLayerOpt.SourdatModleList = new List<DataModel>();
                dataContext.DataLayerOpt.SourdatModleList.AddRange(dataModelsOPList);
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList);
                stopwatch.Stop();
                SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
                dataContext.InteractiveShow.LogShow("新数据阶段小于传入阶段数据阶段，不进行案件数据优选：" + dataContext.DataLayerOpt.OptimizationXml);
                return;
            }

            if (!dataModelsOPList.Any())
            {
                dataContext.InteractiveShow.LogShow("优选结果不存在,将分析结果赋值给优选结果！");
                #region 屏蔽补充数据优选功能
                //if (!string.IsNullOrEmpty(dataContext.DataLayerAns.BcXML))
                //{
                //    XmlDocument nodeDocument = new XmlDocument();
                //    nodeDocument.LoadXml(dataContext.DataLayerAns.BcXML);
                //    XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                //    DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(nodeDocument);
                //    dataContext.InteractiveShow.LogShow("执行补充数据优选开始，补充数据内容" + dataContext.DataLayerAns.BcXML);
                //    MergConfig(dataSoursModel.dataModelList, dataModelsOPList, "1");
                //    CaseElmentOptimization(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "", dataSoursModel.dataModelList);
                //    dataModelsOPList = dataSoursModel.dataModelList;
                //}
                //else
                //{
                //    dataModelsOPList = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
                //}
                #endregion

                dataModelsOPList = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
                dataContext.DataLayerOpt.SourdatModleList = new List<DataModel>();
                dataContext.DataLayerOpt.SourdatModleList.AddRange(dataModelsOPList);
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList);
            }
            else
            {
                if (!string.IsNullOrEmpty(dataContext.DataLayerAns.BcXML))
                {

                    try
                    {
                        #region 屏蔽补充数据优选功能
                        //XmlDocument nodeDocument = new XmlDocument();
                        //nodeDocument.LoadXml(dataContext.DataLayerAns.BcXML);
                        //XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                        //DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(nodeDocument);
                        //dataContext.InteractiveShow.LogShow("执行补充数据优选开始，补充数据内容" + dataContext.DataLayerAns.BcXML);
                        //MergConfig(dataSoursModel.dataModelList, dataModelsOPList, "1");
                        //CaseElmentOptimization(dataSoursModel.dataModelList, "", dataModelsOPList);
                        #endregion

                    }
                    catch (Exception)
                    {

                        dataContext.DataLayerAns.BcXML = "";
                    }


                }
                dataContext.InteractiveShow.LogShow("进行案件要素优选！@");
                MergConfig(dataModelAsisList, dataModelsOPList, "1");

                XmlDocument xmlDocument1 = new XmlDocument();
                xmlDocument1 = XmlUtility.DataModelByXml(dataModelsOPList);
                CaseElmentOptimization(dataModelAsisList, "", dataModelsOPList);
                if (dataContext.DataLayerOpt.SourdatModleList == null)
                {
                    dataContext.DataLayerOpt.SourdatModleList = new List<DataModel>();
                }
                dataContext.DataLayerOpt.SourdatModleList = dataModelsOPList;
                if (dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
                {
                    dataContext.DataLayerOpt.SourdatModleList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.State != "2").ToList();
                    dataContext.DataLayerOpt.SourdatModleList = dataContext.DataLayerOpt.SourdatModleList.Where(a => a.sourceData.sourceList.FirstOrDefault(b => b.AnalysisStatus != "0") != null).ToList();
                }
                //根据对象生成xml出现父子级错误；
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList.ToList());
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(dataContext.DataLayerOpt.OptimizationXml.OuterXml);
            }
            stopwatch.Stop();
            SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
        }

        /// <summary> 
        /// 案件信息优选
        /// </summary>
        /// <param name="dataModelAsisList">分析数据结果</param>
        /// <param name="prentID"></param>
        /// <param name="dataModelsOPList">上次优先结果数据</param>
        public void CaseElmentOptimization(List<DataModel> dataModelAsisList, string prentID, List<DataModel> dataModelsOPList)
        {
            List<DataModel> dataModelsAissNodeList = new List<DataModel>();
            if (dataContext.DataLayerAns.CaseCausesList != null && dataContext.DataLayerAns.CaseCausesList.Count > 0)
            {// && a.XmlPath.IndexOf("案由要素") < 0
                
                dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID).ToList();
                //if (dataContext.DataLayerAns.CaseType.ToLower()== "ldzc")
                //{
                //    dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID).ToList();
                //}
                //else
                //{
                //    dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID && a.XmlPath.IndexOf("案由要素") < 0).ToList();
                //}
                
                

            }
            else
            {
                dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID).ToList();
            }
            if (dataModelsAissNodeList.Count > 0)
            {
                var asisNodeIds = dataModelsAissNodeList.Select(x => x.ID).ToList();
                foreach (DataModel dataModelAsisNode in dataModelsAissNodeList)
                {
                    if(dataModelAsisNode!=null && dataModelAsisNode.AttributesList != null)
                    {
                        foreach (var attmode in dataModelAsisNode.AttributesList)
                        {
                            if (attmode.sourceList != null && attmode.sourceList.Count > 0 && attmode.sourceList.FirstOrDefault(a => a.IsCheck == "1") == null)
                            {
                                attmode.sourceList[0].IsCheck = "1";
                            }
                        }
                    }
                    
                    Xmllable xmllableCofigs = OptimizConfig.XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelAsisNode.XmlPath);
                    if (xmllableCofigs?.Condition!=null && !string.IsNullOrEmpty(xmllableCofigs?.Condition))
                    {
                        string sourdata = xmllableCofigs.Condition.Split('=')[0];
                        string type=xmllableCofigs.Condition.Split('=')[1];
                        if (dataContext.DataLayerAns.SourceCode.ToLower()== sourdata.ToLower())
                        {
                            xmllableCofigs.Type = type;
                        }
                    }
                    if (xmllableCofigs != null && xmllableCofigs.Type == "b")
                    {
                        dataContext.InteractiveShow.LogShow("进入优先模式B" + xmllableCofigs.Xmlpath);
                        //单一数据源优选
                        #region 单一数据源
                        string parentid = "";
                        DataModel dataOpModel = new DataModel();
                        string pathtext = "";
                        if (xmllableCofigs.Xmlpath.IndexOf(@"案件审理阶段/") > -1)
                        {
                            pathtext = xmllableCofigs.Xmlpath.Split(new string[] { @"案件审理阶段/" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        }
                        if (dataModelsOPList.FirstOrDefault(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext) && a.State != "2") == null)
                        {
                            string xmlpath = "";
                            for (int i = 0; i < xmllableCofigs.Xmlpath.Split('/').Length - 1; i++)
                            {
                                if (xmlpath == "")
                                {
                                    xmlpath = xmllableCofigs.Xmlpath.Split('/')[i];
                                }
                                else
                                {
                                    xmlpath = xmlpath + "/" + xmllableCofigs.Xmlpath.Split('/')[i];
                                }
                            }
                            if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath && a.State != "2") != null)
                            {
                                parentid = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath).ID;
                                dataModelAsisNode.ParentId = parentid;
                                List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAsisNode);
                                foreach (DataModel aissmodel in dataModelListRestAiss)
                                {
                                    aissmodel.State = "1";
                                    dataModelsOPList.Add(aissmodel);
                                }
                            }
                            else
                            {
                                string xmlp = "";
                                if (xmlpath.IndexOf(@"案件审理阶段/") > -1)
                                {
                                    xmlp = xmlpath.Split(new string[] { @"案件审理阶段/" }, StringSplitOptions.RemoveEmptyEntries)[1];
                                }
                                if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlp && a.State != "2") != null)
                                {
                                    parentid = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlp).ID;
                                    dataModelAsisNode.ParentId = parentid;
                                    List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAsisNode);
                                    foreach (DataModel aissmodel in dataModelListRestAiss)
                                    {
                                        aissmodel.State = "1";
                                        dataModelsOPList.Add(aissmodel);
                                    }
                                }
                            }
                        }
                        else
                        {
                            dataOpModel = dataModelsOPList.FirstOrDefault(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext) && a.State != "2");
                            string modesours = dataOpModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceCode;
                            string soursnameopid = OptimizConfig.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == modesours.ToLower()).id.ToString();
                            string soursnameasisid = OptimizConfig.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).id.ToString();
                            int opsum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameopid);
                            int assum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameasisid);
                            if (assum < opsum)
                            {

                                if (dataModelsOPList.FirstOrDefault(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext) && a.State != "2") != null)
                                {
                                    List<DataModel> dataModelListOp = dataModelsOPList.Where(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext) && a.State != "2").ToList();
                                    foreach (DataModel dataop in dataModelListOp)
                                    {
                                        List<DataModel> dataModelListRest = SubordinateDataModelList(dataModelsOPList, dataop);
                                        parentid = dataop.ParentId;
                                        foreach (DataModel dataModelOP in dataModelListRest)
                                        {
                                            dataModelOP.State = "2";
                                        }
                                    }
                                }

                                foreach (DataModel dataModelAiss in dataModelsAissNodeList.Where(a => a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext))
                                {
                                    if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == dataModelAiss.XmlPath && a.State != "2") == null)
                                    {
                                        List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAiss);
                                        dataModelListRestAiss.FirstOrDefault(a => a.ID == dataModelAiss.ID).ParentId = parentid;
                                        dataModelListRestAiss = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelListRestAiss));
                                        foreach (DataModel aissmodel in dataModelListRestAiss)
                                        {
                                            aissmodel.State = "1";
                                            dataModelsOPList.Add(aissmodel);
                                        }
                                    }
                                }
                            }
                            if (assum == opsum)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext) && a.State != "2") != null)
                                {
                                    List<DataModel> dataModelListOp = dataModelsOPList.Where(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext) && a.State != "2").ToList();
                                    foreach (DataModel dataop in dataModelListOp)
                                    {
                                        List<DataModel> dataModelListRest = SubordinateDataModelList(dataModelsOPList, dataop);
                                        parentid = dataop.ParentId;
                                        foreach (DataModel dataModelOP in dataModelListRest)
                                        {
                                            dataModelOP.State = "2";
                                        }
                                    }
                                }

                                foreach (DataModel dataModelAiss in dataModelsAissNodeList.Where(a => (a.XmlPath == xmllableCofigs.Xmlpath || a.XmlPath == pathtext)))
                                {

                                    List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAiss);
                                    dataModelListRestAiss.FirstOrDefault(a => a.ID == dataModelAiss.ID).ParentId = parentid;
                                    dataModelListRestAiss = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelListRestAiss));
                                    foreach (DataModel aissmodel in dataModelListRestAiss)
                                    {
                                        aissmodel.State = "1";
                                        dataModelsOPList.Add(aissmodel);
                                    }

                                }

                            }
                        }

                        #endregion
                    }
                    else
                    {
                        #region 多数据源优选

                        List<DataModel> dataModelListAsis = new List<DataModel>();//分析下级循环合集
                        List<DataModel> dataModelListOP = new List<DataModel>();//优选下级循环合集
                        dataModelListAsis = dataModelAsisList;
                        dataModelListOP = dataModelsOPList;
                        Xmllable xmllableCofig = OptimizConfig.XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelAsisNode.XmlPath);
                        if (xmllableCofig != null)
                        {
                            bool determine = true;
                            if (xmllableCofig.ConditionList.Count > 0)
                            {
                                try
                                {
                                    determine = ConditionDetermine(xmllableCofig.ConditionList);
                                }
                                catch (Exception ef)
                                {
                                    dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，配置信息：" + JsonConvert.SerializeObject(ef.ToString()));
                                    dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，错误信息：" + ef.ToString());
                                }
                            }
                            DataModel dataModelOpSging = new DataModel();
                            if (determine)
                            {
                                int goon = 1;
                                if (xmllableCofig.Type == "a")
                                {
                                    Dictionary<string, string> sginDic = new Dictionary<string, string>();
                                    //分析数据标识是否有值
                                    bool isEffective = false;
                                    foreach (var element in xmllableCofig.SignnodeList.NodeList)
                                    {
                                        bool min = true;
                                        //是否覆盖
                                        bool isCover = false;
                                        if (element.ConditionList != null && element.ConditionList.Count() > 0)
                                        {
                                            var firstCondition = element.ConditionList.FirstOrDefault();
                                            if(firstCondition?.IsCover!=null && firstCondition.IsCover=="1")
                                                isCover = true;
                                            //根据业务配置条件，判定被优选节点是否符合条件配置，如果符合返回true，否则返回false；
                                            min = ConditionDetermine(element.ConditionList, dataModelListAsis);
                                        }
                                        if (min)
                                        {
                                            if (dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code) != null)
                                            {
                                                string elementvalue = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                                isEffective = true;
                                                sginDic.Add(element.Code, elementvalue);
                                            }
                                            else
                                            {
                                                sginDic.Add(element.Code, null);
                                            }
                                        }
                                        //如果配置覆盖，则将优选结果
                                        if(isCover)
                                        {
                                            var opModelDelList = dataModelListOP.Where(x => x.XmlPath == xmllableCofig.Xmlpath && !asisNodeIds.Contains(x.ID)).ToList();
                                            foreach (var item in opModelDelList)
                                            {
                                                var currtDelModels = SubordinateDataModelList(dataModelsOPList, item);
                                                if(currtDelModels!=null && currtDelModels.Any())
                                                {
                                                    var delModelIds = currtDelModels.Select(x => x.ID).ToList();
                                                    dataModelListOP.RemoveAll(x => delModelIds.Contains(x.ID));
                                                }
                                                
                                            }
                                        }

                                    }
                                    if (isEffective == false)
                                        goon = 0;
                                    List<DataModel> dataSingList = new List<DataModel>();
                                    string xml = "";
                                    if (xmllableCofig.Xmlpath.IndexOf(@"案件审理阶段/") > -1)
                                    {
                                        xml = xmllableCofig.Xmlpath.Split(new string[] { @"案件审理阶段/" }, StringSplitOptions.RemoveEmptyEntries)[1];
                                    }
                                    if (dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath || a.XmlPath == xml) != null)
                                    {
                                        dataSingList = dataModelListOP.Where(a => a.XmlPath == xmllableCofig.Xmlpath || a.XmlPath == xml).ToList();
                                        /*
                                         是否相同节点数据
                                        只要标识中有一项值相同即为相同节点
                                         */
                                        bool isSameData = false;
                                        foreach (var dic in sginDic)
                                        {
                                            #region TODO:ZSW 优选旧逻辑
                                            //if (dic.Value == null)
                                            //{
                                            //    if (dataSingList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key) == null) != null)
                                            //    {
                                            //        dataSingList = dataSingList.Where(a => (a.XmlPath == xmllableCofig.Xmlpath || a.XmlPath == xml) && a.AttributesList.FirstOrDefault(b => b.Name == dic.Key) == null).ToList();
                                            //    }

                                            //    else
                                            //    {
                                            //        dataSingList = new List<DataModel>();
                                            //        //对于不符合标识的数据不进行下一步操作；
                                            //        goon = 0;
                                            //    }
                                            //}
                                            //else
                                            //{
                                            //    try
                                            //    {
                                            //        if (dataModelListOP.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                            //   b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == dic.Value) != null) != null) != null)
                                            //        {
                                            //            dataSingList = dataSingList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                            //          b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == dic.Value) != null) != null).ToList();
                                            //        }
                                            //        else
                                            //        {
                                            //            dataSingList = new List<DataModel>();
                                            //        }
                                            //    }
                                            //    catch
                                            //    {
                                            //        dataSingList = new List<DataModel>();
                                            //    }
                                            //}
                                            #endregion

                                            if(!string.IsNullOrWhiteSpace(dic.Value))
                                            {
                                                try
                                                {
                                                    if (dataModelListOP.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                               b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && (s.SaveValue == dic.Value || s.SaveValue==null || s.SaveValue=="" )) != null) != null) != null)
                                                    {
                                                        dataSingList = dataSingList.Where(a => a.AttributesList.FirstOrDefault(b => b.Name == dic.Key &&
                                                      b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && (s.SaveValue == dic.Value || s.SaveValue == null || s.SaveValue == "")) != null) != null).ToList();
                                                        //isSameData = true;
                                                    }
                                                    else
                                                    {
                                                        dataSingList = new List<DataModel>();
                                                    } 
                                                }
                                                catch
                                                {
                                                    dataSingList = new List<DataModel>();
                                                }
                                            }
                                        } 
                                        //成功1xmlpath="zhengju/xiangqing"

                                        //if (isSameData == false)
                                        //    dataSingList = new List<DataModel>();
                                        //当前的IF用于判断，在标识基础上，进行条件判定，如果条件不符合，则sginDic的数量就会为0
                                        if (sginDic.Count() == 0)
                                        {
                                            dataSingList = new List<DataModel>();
                                            //对于不符合标识的数据不进行下一步操作；
                                            goon = 0;
                                        }
                                        if (dataSingList != null && dataSingList.Count > 0)
                                        {
                                            dataModelOpSging = dataSingList.First();
                                            if (dataModelOpSging != null)
                                            {
                                                dataModelListOP = SubordinateDataModelList(dataModelsOPList, dataModelOpSging);
                                                List<DataModel> parentNodeModel = ParendNodeDataModelList(dataModelsOPList, dataModelOpSging);
                                                dataModelListOP.AddRange(parentNodeModel);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.State != "2");
                                }
                                if (goon == 1)
                                {
                                    OptimizationData(dataModelAsisNode, dataModelOpSging, xmllableCofig, dataModelListOP, dataModelAsisList, OptimizConfig.Sourcedatadefine);
                                }
                            }
                            if (dataModelOpSging != null && dataModelOpSging.sourceData != null)
                            {
                                CaseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelListOP);
                            }
                            foreach (DataModel opModel in dataModelListOP)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID && a.State == opModel.State) != null)
                                {

                                    DataModel model = dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID);
                                    model = opModel;

                                }
                                else
                                {
                                    dataModelsOPList.Add(opModel);
                                }
                            }
                        }
                        else
                        {
                            //进入到该方法块的内容，都是属于没有业务配置的节点处理方式的；
                            DataModel dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2");
                            if (dataModelOpSging == null)
                            {
                                //获取上级节点信息
                                string parentxml = "";
                                List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();

                                string lastpathNodeName = pathlist[pathlist.Count - 1];

                                pathlist.RemoveAt(pathlist.Count - 1);
                                if (pathlist.Count() > 0)
                                {
                                    parentxml = string.Join("/", pathlist);
                                    if (lastpathNodeName == "证据要素")
                                    {
                                        //如果是证据要素要进行整体的添加处理
                                        DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                        if (nodeParent != null)
                                        {
                                            //添加子级信息
                                            List<DataModel> dataModelEvid = new List<DataModel>();
                                            dataModelEvid = SubordinateDataModelList(dataModelAsisList, dataModelAsisNode);
                                            string messagss = JsonConvert.SerializeObject(dataModelEvid);
                                            var newevidmodel = JsonConvert.DeserializeObject<List<DataModel>>(messagss);
                                            newevidmodel[0].ParentId = nodeParent.ID;
                                            dataModelsOPList.AddRange(newevidmodel);
                                        }

                                    }
                                    else
                                    {
                                        try
                                        {
                                            if (parentxml.IndexOf("证据要素") > -1)
                                            {
                                                parentxml = "";
                                            }
                                            if (!string.IsNullOrEmpty(parentxml))
                                            {
                                                try
                                                {

                                                }
                                                catch (Exception)
                                                {

                                                    throw;
                                                }
                                                CaseNodeUpdate(dataModelListOP, parentxml);
                                                DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                                if (nodeParent != null)
                                                {
                                                    string message = JsonConvert.SerializeObject(dataModelAsisNode);
                                                    DataModel dataModelAddNode = JsonConvert.DeserializeObject<DataModel>(message);
                                                    dataModelAddNode.ParentId = nodeParent.ID;
                                                    dataModelListOP.Add(dataModelAddNode);
                                                    dataModelsOPList.Add(dataModelAddNode);
                                                }
                                            }
                                        }
                                        catch (Exception)
                                        {

                                           
                                        }  
                                        
                                    }

                                }
                            }
                            else
                            {
                                try
                                {
                                    List<DataModel> opList = dataModelListOP.Where(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2").ToList();
                                    if (opList.Count > 0)
                                    {
                                        if (!ISsameNode(opList, dataModelAsisNode))
                                        {
                                            //不存在该节点
                                            string parentxml = "";
                                            List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                            pathlist.RemoveAt(pathlist.Count - 1);
                                            parentxml = string.Join("/", pathlist);
                                            if (string.IsNullOrEmpty(parentxml))
                                            {
                                                parentxml = dataModelAsisNode.XmlPath;
                                            }
                                            else
                                            {
                                                CaseNodeUpdate(dataModelListOP, parentxml);
                                            }
                                            DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                            string message = JsonConvert.SerializeObject(dataModelAsisNode);
                                            DataModel dataModelAddNode = JsonConvert.DeserializeObject<DataModel>(message);
                                            dataModelAddNode.ParentId = nodeParent.ID;
                                            dataModelListOP.Add(dataModelAddNode);
                                        }
                                        else
                                        {
                                            string parentxml = "";
                                            List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();

                                            string lastpathNodeName = pathlist[pathlist.Count - 1];

                                            pathlist.RemoveAt(pathlist.Count - 1);
                                            if (pathlist.Count() > 0)
                                            {
                                                parentxml = string.Join("/", pathlist);
                                                if (lastpathNodeName == "证据要素")
                                                {
                                                    //如果是证据要素要进行整体的添加处理
                                                    DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                                    List<DataModel> modelsRomveList = SubordinateDataModelList(dataModelListOP, dataModelOpSging);
                                                    for (int i = 0; i < modelsRomveList.Count; i++)
                                                    {
                                                        modelsRomveList[i].State = "2";
                                                    }
                                                    if (nodeParent != null)
                                                    {
                                                        //添加子级信息
                                                        List<DataModel> dataModelEvid = new List<DataModel>();
                                                        dataModelEvid = SubordinateDataModelList(dataModelAsisList, dataModelAsisNode);
                                                        string messagss = JsonConvert.SerializeObject(dataModelEvid);
                                                        var newevidmodel = JsonConvert.DeserializeObject<List<DataModel>>(messagss);
                                                        newevidmodel[0].ParentId = nodeParent.ID;
                                                        dataModelsOPList.AddRange(newevidmodel);
                                                    }

                                                }

                                            }
                                        }

                                    }
                                }
                                catch (Exception)
                                {

                                    
                                }
                                
                            }
                            CaseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelsOPList);
                        }
                        #endregion
                    }
                }
            }
        }


        /// <summary>
        /// 阶段定位配置文件
        /// </summary>
        /// <param name="causeLocalXml"></param>
        /// <param name="causeStageXml"></param>
        /// <returns></returns>
        private List<DOCLocationModel> GetLocationModels(string causeLocalXml, string causeStageXml)
        {
            List<CTLocationModel> cTLocations = new List<CTLocationModel>();
            ParseLocationConfig locationConfigM = new ParseLocationConfig();
            var locationModels = locationConfigM.GetLocationModel(causeLocalXml, causeStageXml, dataContext.DataLayerOpt.OptimizationXml, dataContext.DataLayerAns.CaseType, dataContext.DataLayerAns.SourceCode);
            return locationModels;
        }


        #region 处理回填信息
        /// <summary>
        /// 对属性进行添加
        /// </summary>
        /// <param name="changeDataModel"></param>
        public void A_attrClass(ChangeDataModel changeDataModel)
        {
            DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
            var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
            List<StageProcessModel> stageProcessModelList = new List<StageProcessModel>();
            List<DataModel> SourceDataModelList = new List<DataModel>();
            if (dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
            {
                SourceDataModelList = dataContext.DataLayerOpt.SourdatModleList;
            }
            else
            {
                if (anjiancunchuList.Count > 0)
                {
                    DataSoursModel dataSoursModel = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                    SourceDataModelList = dataSoursModel.dataModelList;
                }
            }

            if (SourceDataModelList.Count > 0)
            {
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
                DataModel dataModelRootm = SourceDataModelList.FirstOrDefault(a => a.ID == changeDataModel.NodeId);
                List<DataModel> dataModelAsisList = xmlUtilCommon.SubParentDateModel(SourceDataModelList, dataModelRootm);
                dataModelAsisList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelAsisList));
                xmlUtilCommon.DataModelIDByReset(dataModelAsisList, "", "");
                SateLoadeOptimization(SourceDataModelList, dataModelAsisList);
                dataContext.DataLayerAns.AnalysisResultsDataModel = new DataSoursModel();
                dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList = dataModelAsisList;
                string attName = changeDataModel.ChangeAttrName.Trim();
                string attValue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue.Trim());
                if (!string.IsNullOrEmpty(attName) && !string.IsNullOrEmpty(attValue) && !string.IsNullOrEmpty(changeDataModel.NodeId))
                {
                    DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == changeDataModel.NodeId);
                    if (dataModelRoot != null)
                    {
                        List<Sourcedata> sourceDatade = new List<Sourcedata>();
                        List<Xmllable> xmllableList = new List<Xmllable>();
                        //属性值
                        AttributeInfo attribute = dataModelRoot.AttributesList.FirstOrDefault(a => a.Name == attName);
                        if (attribute!=null)
                        {
                            attribute.sourceList = attribute.sourceList.Where(a => !string.IsNullOrEmpty(a.SaveValue)).ToList();
                            if (attribute.sourceList.FirstOrDefault(a=> a.IsCheck=="1")==null)
                            {
                                if (attribute.sourceList!=null && attribute.sourceList.Count>0)
                                {
                                    attribute.sourceList[0].IsCheck = "1";
                                }
                                
                            }
                        }
                        Source source = new Source();
                        source.SaveValue = attValue;
                        source.SourceCode = dataContext.DataLayerAns.SourceCode;

                        if (attribute == null || attribute.sourceList.Count==0)
                        {
                            source.IsCheck = "1";
                            attribute = new AttributeInfo();
                            attribute.Name = attName;
                            attribute.sourceList = new List<Source>();
                            attribute.sourceList.Add(source);
                            dataModelRoot.AttributesList.Add(attribute);
                        }
                        else
                        {
                            if (dataModelRoot.XmlPath.IndexOf("案由要素") == -1)
                            {
                                sourceDatade = OptimizConfig.Sourcedatadefine[0].SourcedataList;
                                xmllableList = OptimizConfig.XmllableList;
                            }
                            else
                            {
                                sourceDatade = OptimizeElement.Sourcedatadefine[0].SourcedataList;
                                xmllableList = OptimizeElement.CaseTypeList[0].XmlFactTypeList[0].XmllableList;
                            }

                            if (sourceDatade != null)
                            {
                                Sourcedata sourcedataop = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == attribute.sourceList.FirstOrDefault(b => b.IsCheck == "1").SourceCode.ToLower());
                                Sourcedata sourcedataas = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                                Xmllable xmllable = xmllableList.FirstOrDefault(a => a.Xmlpath == dataModelRoot.XmlPath);

                                int assum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataas.id.ToString());
                                if (xmllable.ElementList != null && !string.IsNullOrEmpty(attName))
                                {
                                    LdtJudge.DataEngine.Model.XMLConfigModel.DataStores.Element element = xmllable.ElementList.FirstOrDefault(a => a.Name == attName);
                                    if (element != null && !string.IsNullOrEmpty(element.Priority))
                                    {
                                        assum = ListByCount(element.Priority.Split('>').ToList(), sourcedataas.id.ToString());
                                    }
                                }
                                if (sourcedataop != null)
                                {
                                    int opsum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataop.id.ToString());
                                    if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                    {
                                        attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                        if (assum <= opsum)
                                        {
                                            for (int i = 0; i < attribute.sourceList.Count; i++)
                                            {
                                                attribute.sourceList[i].IsCheck = "0";
                                            }
                                            attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).IsCheck = "1";
                                        }
                                    }
                                    else
                                    {
                                        if (assum <= opsum)
                                        {
                                            for (int i = 0; i < attribute.sourceList.Count; i++)
                                            {
                                                attribute.sourceList[i].IsCheck = "0";
                                            }
                                            source.IsCheck = "1";
                                        }
                                        else
                                        {
                                            source.IsCheck = "0";
                                        }
                                        attribute.sourceList.Add(source);
                                    }
                                }
                                else
                                {
                                    if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                    {
                                        attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                    }
                                    else
                                    {
                                        if (assum != 999)
                                        {
                                            for (int i = 0; i < attribute.sourceList.Count; i++)
                                            {
                                                attribute.sourceList[i].IsCheck = "0";
                                            }
                                            source.IsCheck = "1";
                                        }
                                        else
                                        {
                                            source.IsCheck = "0";

                                        }
                                        attribute.sourceList.Add(source);
                                    }

                                }

                            }
                        }
                    }
                }

                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(SourceDataModelList);
                dataContext.DataLayerOpt.SourdatModleList = SourceDataModelList;
            }

        }

        /// <summary>
        /// 对节点进行添加
        /// </summary>
        /// <param name="changeDataModel"></param>
        public void A_nodeClass(ChangeDataModel changeDataModel)
        {
            DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
            var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
            List<StageProcessModel> stageProcessModelList = new List<StageProcessModel>();
            List<DataModel> SourceDataModelList = new List<DataModel>();
            if (dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
            {
                SourceDataModelList = dataContext.DataLayerOpt.SourdatModleList;
            }
            else
            {
                if (anjiancunchuList.Count > 0)
                {
                    string b = "781f18610b23430b83e952feaa67cc02";
                    string c = "dca3c2388b0a4adab550d014f41b3b75";
                    DataSoursModel dataSoursModels = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                    SourceDataModelList = dataSoursModels.dataModelList;


                }
            }
            string nodeValue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue.Trim());
            if (dataContext.DataLayerOpt.AppId.ToLower() != "ldt.elementcenterInfoquery")
            {
                nodeValue = HandleNodeAttr(nodeValue);
            }
            string nodeID = changeDataModel.NodeId.Trim();
            List<DataModel> dataModelListOP = new List<DataModel>();
            XmlDocument nodeDocument = new XmlDocument();
            nodeDocument.LoadXml(nodeValue);
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(nodeDocument);
            if (nodeID == "0")
            {
                if (dataSoursModel.dataModelList.Count > 0)
                {
                    dataContext.DataLayerAns.AnalysisResultsDataModel = dataSoursModel;
                    try
                    {
                        //运行卡顿 暂时屏蔽
                        if (dataContext.DataLayerAns.SourceCode!= "evidencedata")
                        {
                            string sfid = string.Empty;
                            var evidContentNode = nodeDocument.SelectSingleNode("descendant-or-self::证据内容/详情");
                            if (evidContentNode != null)
                            {
                                sfid = evidContentNode.Attributes["证据文件ID"].Value;
                            }
                            dataContext.DataLayerAns.Shujuneirong.Sf_id = sfid;
                            AnalysisDataControl analysisDataControl = new AnalysisDataControl(dataContext);
                            analysisDataControl.SaveData(1);
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        dataContext.InteractiveShow.LogShow("保存回填信息错误");
                    }
                    
                    Optimization();
                }

            }
            else
            {
                DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == nodeID);
                if (dataSoursModel != null && dataModelRoot != null)
                {
                    foreach (DataModel model in dataSoursModel.dataModelList)
                    {
                        model.XmlPath = dataModelRoot.XmlPath + "/" + model.XmlPath;
                    }
                    List<DataModel> dataModelAsisList = xmlUtilCommon.SubParentDateModel(SourceDataModelList, dataModelRoot);
                    dataSoursModel.dataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = changeDataModel.NodeId;
                    dataSoursModel.dataModelList.AddRange(dataModelAsisList);
                    XmlDocument xmlDocumentff = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
                    dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackID(xmlDocumentff);
                    SateLoadeOptimization(SourceDataModelList, dataSoursModel.dataModelList);
                    CaseElmentOptimization(dataSoursModel.dataModelList, "", SourceDataModelList);
                    if (SourceDataModelList != null && SourceDataModelList.Count > 0)
                    {
                        dataContext.DataLayerOpt.SourdatModleList = SourceDataModelList.Where(a => a.State != "2").ToList();
                        dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList);
                    }

                }
            }
        }

        /// <summary>
        /// 对属性进行删除
        /// </summary>
        /// <param name="changeDataModel"></param>
        public void D_attrClass(ChangeDataModel changeDataModel)
        {
            string attName = changeDataModel.ChangeAttrName.Trim();
            string attValue = "";
            if (!string.IsNullOrEmpty(attName) && !string.IsNullOrEmpty(changeDataModel.NodeId))
            {
                DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
                var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
                List<DataModel> SourceDataModelList = new List<DataModel>();
                if (dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
                {
                    SourceDataModelList = dataContext.DataLayerOpt.SourdatModleList;
                }
                else
                {
                    if (anjiancunchuList.Count > 0)
                    {
                        DataSoursModel dataSoursModels = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                        SourceDataModelList = dataSoursModels.dataModelList;


                    }
                }
                DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == changeDataModel.NodeId);
                if (dataModelRoot != null)
                {
                    List<Sourcedata> sourceDatade = new List<Sourcedata>();
                    List<Xmllable> xmllableList = new List<Xmllable>();
                    //属性值
                    AttributeInfo attribute = dataModelRoot.AttributesList.FirstOrDefault(a => a.Name == attName);

                    Source source = new Source();
                    source.SaveValue = attValue;
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;

                    if (attribute == null)
                    {
                        source.IsCheck = "1";
                        attribute = new AttributeInfo();
                        attribute.Name = attName;
                        attribute.sourceList.Add(source);
                        dataModelRoot.AttributesList.Add(attribute);
                    }
                    else
                    {
                        if (dataModelRoot.XmlPath.IndexOf("案由要素") == -1)
                        {
                            sourceDatade = OptimizConfig.Sourcedatadefine[0].SourcedataList;
                            xmllableList = OptimizConfig.XmllableList;
                        }
                        else
                        {
                            sourceDatade = OptimizeElement.Sourcedatadefine[0].SourcedataList;
                            xmllableList = OptimizeElement.CaseTypeList[0].XmlFactTypeList[0].XmllableList;
                        }

                        if (sourceDatade != null)
                        {
                            Sourcedata sourcedataop = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == attribute.sourceList.FirstOrDefault(b => b.IsCheck == "1").SourceCode.ToLower());
                            Sourcedata sourcedataas = sourceDatade.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                            if (sourcedataop != null && sourcedataas != null)
                            {
                                Xmllable xmllable = xmllableList.FirstOrDefault(a => a.Xmlpath == dataModelRoot.XmlPath);
                                int opsum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataop.id.ToString());
                                int assum = ListByCount(xmllable.Priority.Split('>').ToList(), sourcedataas.id.ToString());
                                if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                {
                                    foreach (Source sources in attribute.sourceList)
                                    {
                                        source.IsCheck = "0";
                                    }
                                    attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                    if (assum <= opsum)
                                    {
                                        attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).IsCheck = "1";
                                    }
                                }
                                else
                                {
                                    if (assum <= opsum)
                                    {
                                        source.IsCheck = "1";
                                    }
                                    else
                                    {
                                        source.IsCheck = "0";
                                    }
                                    attribute.sourceList.Add(source);
                                }
                            }
                            else
                            {
                                if (attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode) != null)
                                {
                                    attribute.sourceList.FirstOrDefault(a => a.SourceCode == dataContext.DataLayerAns.SourceCode).SaveValue = attValue;
                                }
                                else
                                {
                                    source.IsCheck = "1";
                                    attribute.sourceList.Add(source);
                                }
                            }

                        }
                    }

                    dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(SourceDataModelList);
                    dataContext.DataLayerOpt.SourdatModleList = SourceDataModelList;
                }
            }
        }
        /// <summary>
        /// 对节点进行删除
        /// </summary>
        /// <param name="changeDataModel"></param>
        public void D_nodeClass(ChangeDataModel changeDataModel)
        {
            string nodeID = changeDataModel.NodeId;
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
            var anjiancunchuList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId, "3");
            List<DataModel> SourceDataModelList = new List<DataModel>();
            if (dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
            {
                SourceDataModelList = dataContext.DataLayerOpt.SourdatModleList;
            }
            else
            {
                if (anjiancunchuList.Count > 0)
                {
                    DataSoursModel dataSoursModels = GetDataSoursModel(ReadDataXML(anjiancunchuList[0].Wenjianid));
                    SourceDataModelList = dataSoursModels.dataModelList;


                }
            }
            DataModel dataModelRoot = SourceDataModelList.FirstOrDefault(a => a.ID == nodeID);
            if (dataModelRoot != null)
            {
                List<DataModel> dataModelList = xmlUtilCommon.SubordinateDataModelList(SourceDataModelList, dataModelRoot);
                foreach (DataModel mode in dataModelList)
                {
                    SourceDataModelList.Remove(mode);
                }
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(SourceDataModelList);
                dataContext.DataLayerOpt.SourdatModleList = SourceDataModelList;
            }
        }

        /// <summary>
        /// 去除xml所有节点下的id属性
        /// </summary>
        public string HandleNodeAttr(string xmlContent)
        {
            XDocument xDocument = XDocument.Parse(xmlContent);
            var xElementList = xDocument.Elements();
            if (xElementList != null && xElementList.Any())
            {
                foreach (var item in xElementList)
                {
                    DeleteNodeIdAttr(item);
                }
            }
            var content = xDocument.ToString();
            return content;
        }

        /// <summary>
        /// 加载法官确认要素数据到上下文中
        /// </summary>
        public void LoadJudgeConfirmData(ChangeDataModel changeDataModel)
        {
            if(changeDataModel!=null && !string.IsNullOrWhiteSpace(changeDataModel.ChangeValue))
            {
                string nodeValue = HttpHelp.DeCodeBase64new(65001, changeDataModel.ChangeValue.Trim());
                XmlDocument nodeDocument = new XmlDocument();
                nodeDocument.LoadXml(nodeValue);
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(nodeDocument);
                if (dataSoursModel.dataModelList.Count > 0)
                {
                    dataContext.DataLayerAns.JudgeConfirmDataModel = dataSoursModel;
                }
            }
        }


        /// <summary>
        /// 删除节点id属性
        /// </summary>
        /// <param name="xElement"></param>
        private void DeleteNodeIdAttr(XElement xElement)
        {
            var idAttr = xElement.Attribute("id");
            if (idAttr != null)
            {
                idAttr.Remove();
            }
            var childs = xElement.Elements();
            if (childs != null && childs.Any())
            {
                foreach (XElement child in childs)
                {
                    DeleteNodeIdAttr(child);
                }
            }
        }
        #endregion


    }

    public class MergeModel
    {
        /// <summary>
        /// 分析结果相同文书比较结果
        /// </summary>
        public string AsisModle { get; set; }

        /// <summary>
        /// 优选结果相同文书比较结果
        /// </summary>
        public string OPModle { get; set; }

        /// <summary>
        /// 相同文书配置
        /// </summary>
        public XmlMultipleConfig xmlMultiple { get; set; }
    }
}
